const eventService = require('../service/event.service')
const {
	USER_ALREADY_REGISTERED,
	REGISTER_LIMIT,
	USER_NOT_REGISTERED
} = require('../config/error')

const verifyRegister = async (ctx, next) => {
	try {
		const { event_id, user_id } = ctx.params
		const isRegister = await eventService.isRegister(event_id, user_id)
		console.log(isRegister)
		if (isRegister) {
			ctx.app.emit('error', USER_ALREADY_REGISTERED, ctx)
			return
		}
		await next()
	} catch (error) {}
}

const verifyNotRegister = async (ctx, next) => {
	try {
		const { event_id, user_id } = ctx.params
		const isRegister = await eventService.isRegister(event_id, user_id)
		if (!isRegister) {
			ctx.app.emit('error', USER_NOT_REGISTERED, ctx)
			return
		}
		await next()
	} catch (error) {}
}

const verifyLimit = async (ctx, next) => {
	const { event_id } = ctx.params
	const isLimit = await eventService.isLimit(event_id)
	const { registration_limit, registered_count } = isLimit[0]
	if (registration_limit === registered_count) {
		ctx.app.emit('error', REGISTER_LIMIT, ctx)
		return
	}
	await next()
}

module.exports = {
	verifyRegister,
	verifyLimit,
	verifyNotRegister
}
